import baseUrl from './config.js';

function request(obj) {
	return new Promise((resolve, reject) => {
		let method = obj.method || 'GET';
		let url = '';
		let data = obj.data || {};
		let token = uni.getStorageSync('userToken');
		let header = '';
		let facility = uni.getSystemInfoSync().platform; //设备
		let success = obj.success; //成功返回
		let fail = obj.fail; //错误回调

		// 根据设备调整ajax请求
		if(obj.url.indexOf('http://')>=0){
			url = baseUrl + obj.url
		}else if (facility === 'android') {
			url = baseUrl + obj.url
		} else {
			console.log('======是H5======');
			url = baseUrl + obj.url
		}
		//判断登录还是其他请求添加token信息
		if (obj.url === '/loginExt') {
			header = {
				'Content-Type': 'application/json'
			}
		}else if(obj.url.indexOf('http://')>=0){
			header = {}
		} else {
			header = {
				'Content-Type': 'application/json',
				'Authorization': 'Bearer ' + token,
			}
		}

		/*请求方法*/
		uni.request({
			url: url,
			data: data,
			method: method,
			header: header,
			success: ((res) => {
				let code = res.data.code;
				let entity = res.data;
				console.log(res,'===12341234324');
				if (code === 403 || code === 10401) {
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return;
				} else if (code === 200) {
					resolve(entity)
				} else {
					if(obj.url.indexOf('http://')<0){
						uni.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000
						})
					}
					reject(entity)
				}
			})
			// fail((error) => {
			// 	console.log(error, 'error//////error')
			// })
		})
	})
}

export default request
